package org.whuims.job;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.whuims.entity.Paragraph;
import org.whuims.service.document.DocumentService;
import org.whuims.service.paragraph.ParagraphService;
import org.whuims.service.paragraph.ParagraphSolrService;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by zhongwei on 2017/6/16.
 */
@Component
@EnableScheduling
public class ParagraphJob {

    @Autowired
    private ParagraphService paragraphService;
    @Autowired
    private ParagraphSolrService paragraphSolrService;
    @Autowired
    private DocumentService documentService;

    @Scheduled(cron = "0 0 0 * * ?")
    public void run() {
        List<Long> docIds = documentService.getAllId();
        Set<Long> docIdSet = new HashSet<>(docIds);
        Iterable<Paragraph> paragraphs = paragraphService.findAll();
        List<Paragraph> paragraphList = new ArrayList<>();
        List<String> paragraphIdList = new ArrayList<>();
        for (Paragraph paragraph : paragraphs) {
            paragraphList.add(paragraph);
        }
        for (Paragraph paragraph : paragraphList) {
            Long docId = paragraph.getDocumentId();
            if (!docIdSet.contains(docId)) {
                paragraphService.delete(paragraph.getId());
                paragraphIdList.add(String.valueOf(paragraph.getId()));
            }
        }
        paragraphSolrService.delete(paragraphIdList);
    }
}
